package com.fm.parser.json;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import org.joda.time.DateTime;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author final
 */
public class DateTimeCodec implements FastJsonCodec {
    @Override
    @SuppressWarnings("unchecked")
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        JSONLexer lexer = parser.getLexer();
        try {
            switch (lexer.token()) {
                case JSONToken.LITERAL_INT:
                    return (T) new DateTime(lexer.longValue());
                case JSONToken.NULL:
                    return null;
                default:
                    throw new IllegalArgumentException("not support " + type);
            }
        } finally {
            lexer.nextToken();
        }
    }

    @Override
    public int getFastMatchToken() {
        return JSONToken.LITERAL_INT;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter writer = serializer.getWriter();
        if (object == null) {
            writer.writeNull();
            return;
        }
        writer.writeLong(((DateTime) object).getMillis());
    }

    @Override
    public Class getCoderClass() {
        return DateTime.class;
    }
}
